package com.labbit.platform.commons.utils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;

/**
 * @Description 文件大小工具类
 * @Date 2019-07-28 19:59
 * @Author CHEN YU
 **/
public class FileSizeHelper {

    public static final long ONE_KB = 1024;
    public static final long ONE_MB = ONE_KB * 1024;
    public static final long ONE_GB = ONE_MB * 1024;
    public static final long ONE_TB = ONE_GB * (long) 1024;
    public static final long ONE_PB = ONE_TB * (long) 1024;
    public static final String KB = "KB";
    public static final String MB = "MB";

    /**
     * 获取指定格式文件大小
     */
    public static String getHumanReadableFileSize(long fileSize, long unit, String unitName) {

        if (fileSize == 0) {
            return "0";
        }
        if (fileSize / unit >= 1) {
            double value = fileSize / (double) unit;
            DecimalFormat df = new DecimalFormat("######.##" + unitName);
            return df.format(value);
        }
        return null;
    }

    /**
     * 获取指定文件
     */
    public static long getFileSize(long fileSize, long unit) {

        BigDecimal fileSizeBigDecimal = BigDecimal.valueOf(fileSize);
        BigDecimal unitBigDecimal = BigDecimal.valueOf(unit);
        return fileSizeBigDecimal.divide(unitBigDecimal, RoundingMode.HALF_UP).longValue();
    }
}
